<template>
    <!--    搜索条件-->
    <div class="contentContainer">
        <a-form
                ref="formRef"
                layout="inline"
                :model="searchData">
            <a-form-item label="角色名称">
                <a-input v-model:value="searchData.name"></a-input>
            </a-form-item>
            <a-form-item label="状态">
                <a-select v-model:value="searchData.status" style="width: 200px">
                    <a-select-option :value="undefined">全部</a-select-option>
                    <a-select-option :value="0">有效</a-select-option>
                    <a-select-option :value="1">无效</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item>
                <a-space>
                    <a-button type="primary" @click="load(1)">搜索</a-button>
                    <a-button type="default" @click="reset()">重置</a-button>
                </a-space>
            </a-form-item>
        </a-form>
    </div>
    <!--表格-->
    <div class="contentContainer">
        <a-button type="primary" @click="openModal({})" style="margin-bottom: 10px">新增</a-button>
        <a-table bordered
                 size="small"
                 :pagination="false"
                 :dataSource="dataSource"
                 :columns="columns">
            <template #bodyCell="{text,index,column,record}">
                <div v-if="column.key == 'status'">
                    {{text == 0 ? '有效' : '无效'}}
                </div>
                <div v-if="column.key == 'action'">
                    <a-space>
                        <a-button type="primary" @click="openModal(record)">编辑</a-button>
                        <a-popconfirm
                                title="删除数据后无法再次查看！是否确认删除?"
                                ok-text="是"
                                cancel-text="否"
                                @confirm="okDelete(record.id)"
                        >
                            <a-button type="danger">删除</a-button>
                        </a-popconfirm>
                        <a-button type="primary" ghost @click="openAuthorizationDrawer(record.id)">授权</a-button>
                    </a-space>
                </div>
            </template>
        </a-table>
            <a-pagination style="margin-top: 10px; text-align: right"
                          v-model:current="pagination.current"
                          v-model:pageSize="pagination.pageSize"
                          show-quick-jumper
                          show-size-changer
                          :total="pagination.total"
                          :show-total="total => `总 ${total} 条数据`"
                          :page-size-options="pageSizeOptions"
                          @change="onPageChange"/>
    </div>
    <!--编辑模态框-->
    <a-modal v-model:visible="visible" :title="modalTitle" @ok="handleOk">
        <a-form
                ref="formRef"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 18 }"
                :model="role">
            <a-form-item label="角色编码">
                <a-input v-model:value="role.code"></a-input>
            </a-form-item>
            <a-form-item label="角色名">
                <a-input v-model:value="role.name"></a-input>
            </a-form-item>
            <a-form-item label="生效日期">
                    <a-date-picker show-time v-model:value="role.startDate" :disabled-date="disabledDateStart"/>
            </a-form-item>
            <a-form-item label="失效日期">
                    <a-date-picker show-time
                                   v-model:value="role.endDate"
                                   :disabled-date="disabledDateEnd"
                                   :disabled="role.status==0"/>
            </a-form-item>
            <a-form-item label="状态">
                <a-switch v-model:checked="role.status"
                          :checked-value="0"
                          :un-checked-value="1"
                          checked-children="有效"
                          un-checked-children="无效"
                          @change="switchChangeHandler"/>
            </a-form-item>
            <a-form-item label="备注">
                <a-textarea v-model:value="role.remark"
                            :auto-size="{ minRows: 2, maxRows: 5 }">
                </a-textarea>
            </a-form-item>
        </a-form>
    </a-modal>

    <!--    角色授权抽屉-->
    <a-drawer
            v-model:visible="authorizationVisible"
            title="角色授权"
            placement="right"
            width="400"
            @close="authorizationVisible = false"
    >
        <a-alert
                message="《XX》角色"
                description="权限拥有情况如下，请合理分配~~"
                type="info"
                show-icon
        >
            <template #icon>
                <smile-outlined/>
            </template>
        </a-alert>
        <a-tree
                style="margin-top: 10px"
                v-model:checkedKeys="permissionCheckedKeys"
                :default-expand-all="true"
                :checkStrictly="true"
                checkable
                :field-names="{title: 'name',key: 'id'}"
                :tree-data="permissionList"
                @check="checkedChangeHandler"
        ></a-tree>
        <template #footer>
            <a-space style="float: right">
                <a-button type="default" @click="authorizationVisible = false">取消</a-button>
                <a-popconfirm
                        title="是否确认更改授权信息?"
                        ok-text="是"
                        cancel-text="否"
                        :disabled="permissionCheckedKeys.checked == undefined"
                        @confirm="authorizationHandler"
                >
                    <a-button type="primary" :disabled="permissionCheckedKeys.checked == undefined">授权</a-button>
                </a-popconfirm>
            </a-space>
        </template>
    </a-drawer>
</template>

<script setup>
    import {ref, onMounted} from 'vue'
    import axios from 'axios'
    import {message} from 'ant-design-vue'
    import dayjs from "dayjs";
    import {SmileOutlined} from '@ant-design/icons-vue'

    const searchData = ref({})
    const columns = [
        {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '角色名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '角色编码',
            dataIndex: 'code',
            key: 'code',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
        },
        {
            title: '生效时间',
            dataIndex: 'startDate',
            key: 'startDate',
        },
        {
            title: '失效时间',
            dataIndex: 'endDate',
            key: 'endDate',
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
        },
        {
            title: '操作',
            key: 'action',
            align: 'center'
        }
    ]
    const dataSource = ref([])
    const role = ref({})
    const modalTitle = ref('')
    const roleId = ref()

    const permissionList = ref([])
    const permissionCheckedKeys = ref([])

    const pagination = ref({
        current: 1,
        pageSize: 5,
    })
    const pageSizeOptions = ref(['5', '10', '20', '30', '50', '100'])
    const visible = ref(false)
    const authorizationVisible = ref(false)

    const disabledDateStart = current => {
        return current < dayjs().subtract(1, 'days').endOf('day');
    };

    const disabledDateEnd = current => {
        return current < role.value.startDate;
    };

    const authorizationHandler = () => {
        console.log("授权")
        axios.post('role-permission/authorization', {
            roleId: roleId.value,
            menuIds: permissionCheckedKeys.value.checked
        }).then(rs =>{
            if (rs.data.code == 200){
                message.success("授权成功")
                authorizationVisible.value = false
            }else {
                message.error(rs.data.message)
            }
        })
    }

    const openModal = (obj) => {
        role.value = JSON.parse(JSON.stringify(obj))
        if (obj.id) {
            modalTitle.value = '修改'
            role.value.startDate = dayjs(role.value.startDate)
            role.value.endDate = dayjs(role.value.endDate)
        } else {
            modalTitle.value = '新增'
            role.value.status = 0
            role.value.startDate = dayjs()
        }
        console.log("模态框的用户数据", role.value)
        visible.value = true
    }

    const openAuthorizationDrawer = (id) => {
        roleId.value = id
        axios.get('menu/queryAll').then(rs => {
            if (rs.data.code === 200) {
                permissionList.value = rs.data.data
                authorizationVisible.value = true
            } else {
                message.error(rs.data.message)
            }
        })
        axios.get('role-permission/queryMenuIdsByRoleId/' + id).then(rs => {
            if (rs.data.code === 200) {
                permissionCheckedKeys.value = rs.data.data
            } else {
                message.error(rs.data.message)
            }
        })
    }

    const checkedChangeHandler = (checked, e) => {
        console.log("checked:", checked)
        console.log("e:", e)
        if (e.checked && e.node.parent != undefined) {
            console.log("有父节点")
            console.log("permissionCheckedKeys:", permissionCheckedKeys.value.checked)

            let parent = e.node.parent
            while (parent != undefined) {
                if (checked.checked.indexOf(parent.key) == -1) {
                    console.log("父节点未被选择")
                    permissionCheckedKeys.value.checked.push(parent.key)
                    parent = parent.parent
                } else {
                    return
                }
            }
        }
    }

    const handleOk = () => {
        console.log("提交的用户数据", role.value)
        axios.post('role/saveOrUpdate', role.value).then(rs => {
            if (rs.data.code == 200) {
                if (role.value.id) {
                    message.success("《" + role.value.name + "》角色的数据修改成功")
                } else {
                    message.success("成功添加新角色《" + role.value.name + "》")
                }
                visible.value = false
                load()
            } else {
                message.error(rs.data.message)
            }
        })
    }

    const okDelete = (id) => {
        console.log("要删除的角色的id", id)
        axios.delete('role/deleteById/' + id).then(rs => {
            if (rs.data.code == 200) {
                message.success("删除成功")
                load(1)
            } else {
                message.error(rs.data.message)
            }
        })
    }

    const load = (pageNum) => {
        if (pageNum == 1) {
            pagination.value.current = 1
        }
        console.log("查询的参数", searchData.value)
        axios.get('role/queryPageByCondition', {
            params: {
                username: searchData.value.name,
                status: searchData.value.status,
                pageNum: pagination.value.current,
                pageSize: pagination.value.pageSize,
            }
        }).then(rs => {
            console.log("角色查询结果", rs.data)
            if (rs.data.code == 200) {
                dataSource.value = rs.data.data.records
                pagination.value.total = rs.data.data.total
            }
        })
    }

    const reset = () => {
        searchData.value = {}
        load(1)
    }

    const onPageChange = (pageNum, pageSize) => {
        pagination.value.current = pageNum
        pagination.value.pageSize = pageSize
        load()
    }

    const switchChangeHandler = (checked) => {
        role.value.endDate = checked == 0 ? undefined : dayjs()
    }

    onMounted(() => {
        load()
    })
</script>
